package com.itheima.controller.backend;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

//套餐
@RequestMapping("/setmeal")
@RestController
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;
    //新增
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal ,Integer[] checkgroupIds){
        setmealService.add(setmeal,checkgroupIds);
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }
    //编辑
    @PostMapping("/edit")
    public Result edit(@RequestBody Setmeal setmeal ,Integer[] checkgroupIds){
        setmealService.edit(setmeal,checkgroupIds);
        return new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS);
    }
    //根据id查询套餐
    @GetMapping("/findById")
    public Result findById(Integer id){
        Setmeal setmeal =  setmealService.findById(id);
        return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
    }
    //分页查询
    @PostMapping("/findPage")
    public PageResult edit(@RequestBody QueryPageBean queryPageBean){
        return setmealService.findPage(queryPageBean);
    }
    //图片上传
    @PostMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){//01
        String originalFilename = imgFile.getOriginalFilename();//原始文件名（上传的时候的文件名称）//04
        int index = originalFilename.lastIndexOf(".");//通过.来获取原始文件名的后缀，最后一个点是什么位置，位置后的后缀名//05
        String suffix = originalFilename.substring(index);//开始截取，从点开始截取//06
        String fileName = UUID.randomUUID().toString() + suffix;//随机产生一个文件名（16）位，suffix是一个后缀//03
        //将图片保存到阿里云
        try{//getBytes得到一个byte数组
            String uploadUrl = aliOssUtil.upload(imgFile.getBytes(), fileName);//fileName阿里云里面的名称//02
            //文件上传成功后，需要将文件名称保存到redis中
            String replaced = uploadUrl.replace("https://tliasfzk.oss-cn-beijing.aliyuncs.com/", "");
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES,replaced);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,uploadUrl);
        }catch (Exception e){
            e.printStackTrace();    
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);//异常就是图片上传失败
        }
    }
}
